import Vue from 'vue'
import VueRouter from 'vue-router'

const Login = () =>
  import(/* webpackChunkName: "login_home_welcome" */ '@/views/login')
const Home = () =>
  import(/* webpackChunkName: "login_home_welcome" */ '@/views/Home')
const Welcome = () =>
  import(/* webpackChunkName: "login_home_welcome" */ '@/views/Welcome')

const User = () =>
  import(/* webpackChunkName: "Users_Rights_Roles" */ '@/components/user/User')
const Right = () =>
  import(
    /* webpackChunkName: "Users_Rights_Roles" */ '@/components/power/Right'
  )
const Role = () =>
  import(/* webpackChunkName: "Users_Rights_Roles" */ '@/components/power/Role')

const GoodsCategory = () =>
  import(
    /* webpackChunkName: "Cate_Params" */ '@/components/goods/GoodsCategory'
  )
const GoodsParams = () =>
  import(/* webpackChunkName: "Cate_Params" */ '@/components/goods/GoodsParams')

const GoodsList = () =>
  import(/* webpackChunkName: "GoodsList_Add" */ '@/components/goods/GoodsList')
const AddGoods = () =>
  import(/* webpackChunkName: "GoodsList_Add" */ '@/components/goods/AddGoods')

const Order = () =>
  import(/* webpackChunkName: "Order_Report" */ '@/components/order/Order')
const Report = () =>
  import(/* webpackChunkName: "Order_Report" */ '@/components/report/Report')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: User
      },
      {
        path: '/roles',
        component: Role
      },
      {
        path: '/rights',
        component: Right
      },
      {
        path: '/goods',
        component: GoodsList
      },
      {
        path: '/goods/add',
        component: AddGoods
      },
      {
        path: '/categories',
        component: GoodsCategory
      },
      {
        path: '/params',
        component: GoodsParams
      },
      {
        path: '/orders',
        component: Order
      },
      {
        path: '/reports',
        component: Report
      }
    ]
  }
]

// 避免重复路由导航错误
// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes,
  mode: 'history' // 去掉url中#
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    return next()
  }

  const tokenStr = window.sessionStorage.getItem('token')

  if (!tokenStr) {
    return next('/login')
  }
  next()
})

export default router
